package com.scs.application.config;

import com.scs.application.modules.upms.service.WxmpAccountService;
import com.scs.application.modules.upms.wxmp.handler.LogHandler;
import com.scs.application.modules.upms.wxmp.handler.SubscribeHandler;
import com.scs.application.modules.upms.wxmp.handler.UnsubscribeHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

import static com.itextpdf.styledxmlparser.css.media.MediaFeature.SCAN;
import static me.chanjar.weixin.common.api.WxConsts.EventType.SUBSCRIBE;
import static me.chanjar.weixin.common.api.WxConsts.EventType.UNSUBSCRIBE;
import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType.EVENT;

/**
 * @Description:
 */
@AllArgsConstructor
@Slf4j
@Configuration
public class WxMpConfig {

    private final WxmpAccountService wxmpAccountService;

    @Bean
    public WxMpService wxMpService() {

        Map<String, WxMpConfigStorage> configs = wxmpAccountService.getAllWxMpConfig();

        WxMpService service = new WxMpServiceImpl();
        service.setMultiConfigStorages(configs);
        log.info("add {} wxmp configs", configs.size());
        return service;

    }

    private final LogHandler logHandler;
    private final SubscribeHandler subscribeHandler;
    private final UnsubscribeHandler unsubscribeHandler;

    @Bean
    public WxMpMessageRouter messageRouter(WxMpService wxMpService) {
        final WxMpMessageRouter newRouter = new WxMpMessageRouter(wxMpService);

        // 记录所有事件的日志 （异步执行）
        newRouter.rule().handler(this.logHandler).next();

        // 关注事件
        newRouter.rule().async(false).msgType(EVENT).event(SUBSCRIBE).handler(this.subscribeHandler).end();

        // 取消关注事件
        newRouter.rule().async(false).msgType(EVENT).event(UNSUBSCRIBE).handler(this.unsubscribeHandler).end();

        // 扫码事件
        newRouter.rule().async(false).msgType(EVENT).event(SCAN).handler(this.subscribeHandler).end();


        return newRouter;
    }
}
